package com.hopes.bizz.risk.transfer.handler;

import com.hopes.bizz.risk.control.entity.RiskUnitEntity;
import com.hopes.bizz.risk.control.entity.RiskUnitEventEntity;
import com.hopes.bizz.risk.control.service.RiskUnitEventService;
import com.hopes.bizz.risk.control.service.RiskUnitService;
import com.hopes.bizz.risk.transfer.bean.bo.RiskDataBo;
import com.hopes.bizz.risk.transfer.bean.dto.RiskEventDto;
import com.hopes.bizz.risk.transfer.constant.RiskErrorType;
import com.hopes.bizz.risk.transfer.constant.RiskRequestType;
import com.hopes.bizz.risk.transfer.converter.RiskEventConverter;
import com.hopes.boss.common.core.constant.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author lyb
 * @version 1.0
 * @description: 风险事件
 * @date 2024/2/2 17:07
 */

@Component
@Slf4j
public class RiskEventDataHandler extends AbstractRiskData<RiskEventDto> {

    @Resource
    private RiskUnitEventService riskUnitEventService;

    @Resource
    private RiskUnitService riskUnitService;


    @Override
    public RiskRequestType getRequestType() {
        return RiskRequestType.RISK_EVENT;
    }

    @Override
    protected void saveRiskData(RiskEventDto riskEventDto, RiskDataBo riskDataBo) {
        // 判断绑定的单元是否被删除或者为空
        RiskUnitEntity riskUnit = riskUnitService.getByUid(riskEventDto.getRiskUnitId());
        if (Objects.isNull(riskUnit) || CommonConstants.STATUS_DEL.equals(riskUnit.getDelFlag())) {
            saveErrorLog(riskEventDto, riskDataBo, RiskErrorType.RISK_UNIT_NOT_FOUND);
            return;
        }
        // 判断该风险事件是否存在
        String uid = riskEventDto.getId();
        RiskUnitEventEntity riskUnitEvent = riskUnitEventService.getByUid(uid);
        RiskUnitEventEntity riskUnitEventEntity = RiskEventConverter.INSTANCE.toEntity(riskEventDto);
        riskUnitEventEntity.setRiskUnitId(riskUnit.getId());
        riskUnitEventEntity.setOrgId(riskDataBo.getOrgId());
        // 不存在 保存
        if (Objects.isNull(riskUnitEvent)) {
            riskUnitEventService.save(riskUnitEventEntity);
        } else {
            // 更新
            riskUnitEventEntity.setId(riskUnitEvent.getId());
            riskUnitEventService.updateById(riskUnitEventEntity);
        }
    }
}
